<?php

namespace App\Logic\Auth\Form;

use App\Core\BaseForm;
use App\Core\Exception\DefaultException;
use App\Model\Auth\MenuModel;
use App\Model\Auth\MenuRoleModel;
use App\Model\Auth\RoleModel;
use App\Model\UserModel;
use EasySwoole\Component\Di;
use EasySwoole\ORM\DbManager;
use EasySwoole\Redis\Redis;
use EasySwoole\RedisPool\RedisPool;

class MenuRoleSaveForm extends BaseForm{
    
    public $role_id;
    public $menu_ids;

    public function rules(){
        return [
            'role_id'  => ['required|notEmpty', '角色id', '请选择角色'],
            'menu_ids' => ['required|isArray', '权限', '请正确选择权限'],
        ];
    }

    /**
     * 校验提交数据
     * @return bool
     * @throws DefaultException
     * @throws \EasySwoole\Validate\Exception\Runtime
     */
    public function validate(){
        //生成验证器，方法自动读取rules方法返回的值数据
        $validate = $this->createValidator();

        if(!($check = $validate->validate($this->getAttributes()))){
            throw new DefaultException($validate->getError()->__toString(), 600);
        }

        if ( $this->role_id == RoleModel::ROLE_INSIDE ){
            //throw new DefaultException('该角色不允许编辑');
        }

        if ( RoleModel::getCount(['id'=>$this->role_id]) == 0 ){
            throw new DefaultException('该角色不存在');
        }

        if ( !empty($this->menu_ids) && MenuModel::getCount(['id'=>[$this->menu_ids,'in']]) != count($this->menu_ids) ){
            throw new DefaultException('请正确选择菜单');
        }

        return true;
    }
    
    /**
     * 保存数据
     * @return \App\Core\Output
     * @throws DefaultException
     * @throws \EasySwoole\Mysqli\Exception\Exception
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \EasySwoole\Validate\Exception\Runtime
     * @throws \Throwable
     */
    public function saveData(){
        $this->validate();

        //组装批量数组
        $data = [];
        foreach ($this->menu_ids as $menu_id) {
            $data[] = [
                'role_id' => $this->role_id,
                'menu_id' => $menu_id,
            ];
        }

        DbManager::getInstance()->startTransactionWithCount('write');//开启事务
        try {
            //移除数组
            MenuRoleModel::deleteRecord(['role_id'=>$this->role_id]);
            //插入数据
            if ( !empty($data) ){
                $res = MenuRoleModel::insertMulti($data);

                if( $res->getAffectedRows() != count($data)){
                    throw new DefaultException('数据写入失败');
                }
            }

            DbManager::getInstance()->commitWithCount('write');//提交事务
        }catch (\Exception $e) {
            DbManager::getInstance()->rollbackWithCount('write');//回滚事务
            throw new DefaultException($e->getMessage());
        }
        
        self::clearAuthCache();

        return $this->success();
    }

    private function clearAuthCache(){
        /** @var Redis $cache */
//        $cache = Di::getInstance()->get("REDIS");
        $cache = RedisPool::defer();
        $user_ids = UserModel::makeQueryModel(['role_id'=>$this->role_id])->column();
        if ( !empty($user_ids) ){
            foreach ($user_ids as $user_id) {
                $cache_key = "userInfoAuth:" . $user_id;
                if ( $cache->exists($cache_key) ){ //缓存存在
                    //删除缓存
                    $cache->del($cache_key);
                }
            }
        }
        
    }

}